<template>
  <a-modal
    :visible="visible"
    :title="optTitle"
    :destroyOnClose="true"
    :maskClosable="false"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form-model
      ref="cardForm"
      :model="form"
      :rules="rules"
      :label-col="{span: 6}"
      :wrapper-col="{span: 16}"
    >
      <a-form-model-item prop="accountName" label="开户名称" style="margin-top:10px;">
        <a-input v-model="form.accountName" :max-length="20" />
      </a-form-model-item>
      <a-form-model-item prop="accountNumber" label="银行卡账号">
        <a-input v-model="form.accountNumber" :max-length="50" />
      </a-form-model-item>
      <a-form-model-item prop="openingBank" label="银行卡开户行">
        <a-input v-model="form.openingBank" :max-length="20" />
      </a-form-model-item>
      <a-form-model-item prop="picture" label="银行卡正面照" style="margin-bottom:0px;">
        <ud-upload :length="1" @uploadFile="pictureUpload" :fatherList="picList" />
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
import upload from '@/components/UpLoad'

const fomrMessage = `必填项不能为空`
const formDefault = function () {
  return {
    accountName: '', // 开户名称
    accountNumber: '', // 银行卡账号
    openingBank: '', // 银行卡开户行
    picture: null // 银行卡正面照
  }
}

export default {
  name: 'bank-card-modal',
  props: {
    index: Number,
    bank: Object,
    visible: Boolean
  },
  components: {
    'ud-upload': upload
  },
  data () {
    return {
      optTitle: '',
      form: formDefault(),
      rules: {
        accountName: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        accountNumber: [{ required: true, message: fomrMessage, trigger: 'blur' }, { message: '卡号只能输入纯数字', pattern: /^\d+$/, trigger: 'blur' }],
        openingBank: [{ required: true, message: fomrMessage, trigger: 'blur' }]
        // picture: [{required: true, message: fomrMessage, trigger: 'blur'}]
      }
    }
  },
  computed: {
    picList () {
      return this.form.picture ? [this.form.picture] : []
    }
  },
  methods: {
    pictureUpload (val) {
      this.form.picture = val
    },
    handleCancel () {
      this.$emit('set-bankcard-visible', false)
      this.$refs.cardForm.resetFields()
    },
    handleOk () {
      this.$refs.cardForm.validate(valid => {
        if (valid) {
          this.$emit('handle-bank-card', this.index, this.form)
        }
      })
    }
  },
  watch: {
    // 'form.accountNumber' (newd, old) {
    //   if (!newd.match(/^\d+$/)) {
    //     this.form.accountNumber = old
    //   }
    // },
    visible () {
      if (this.index === 0 || this.index) {
        this.optTitle = '编辑银行卡'
        Object.assign(this.form, this.bank)
      } else {
        this.optTitle = '添加银行卡'
        this.form = formDefault()
      }
    }
  }
}
</script>
